<template>
  <div class="users">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>用户管理</span>
          <div class="header-actions">
            <el-button @click="refreshUsers" :loading="loading">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
            <el-button type="primary" @click="showAddUserModal = true">
              <el-icon><Plus /></el-icon>
              添加用户
            </el-button>
          </div>
      </div>
      </template>

      <!-- 搜索和筛选 -->
        <div class="search-section">
        <el-input
          v-model="searchQuery"
              placeholder="搜索用户名、姓名、邮箱..."
          style="width: 300px; margin-right: 16px;"
          clearable
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-select v-model="roleFilter" placeholder="全部角色" style="width: 120px; margin-right: 16px;" clearable>
          <el-option v-for="role in roles" :key="role.id" :label="role.roleName" :value="role.roleName" />
        </el-select>
        <el-select v-model="statusFilter" placeholder="全部状态" style="width: 120px;" clearable>
          <el-option label="活跃" value="1" />
          <el-option label="禁用" value="0" />
        </el-select>
      </div>

      <el-table :data="filteredUsers" style="width: 100%" v-loading="loading">
        <el-table-column label="用户信息" min-width="200">
          <template #default="{ row }">
                <div class="user-info">
                  <div class="user-avatar">
                <img v-if="row.pic" :src="row.pic" :alt="row.pic" />
                <span v-else class="avatar-placeholder">{{ row.userName }}</span>
                  </div>
                  <div class="user-details">
                <div class="user-name">{{ row.userName }}</div>
                <div class="user-email">{{ row.email }}</div>
                  </div>
                </div>
          </template>
        </el-table-column>
        <el-table-column prop="roleName" label="角色" width="120">
          <template #default="{ row }">
            <el-tag :type="getRoleTagType(row.roleName)">
              {{ row.roleName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="手机号" width="150">
          <template #default="{ row }">
            <el-text v-if="row.phone" type="info">{{ row.phone }}</el-text>
            <el-text v-else type="info" style="color: #999;">未设置</el-text>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="150">
          <template #default="{ row }">
            <el-text type="info">{{ formatDate(row.createTime) }}</el-text>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right" align="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="viewUser(row)">查看</el-button>
            <el-button type="warning" size="small" @click="editUser(row)">编辑</el-button>
            <el-button 
              type="danger" 
              size="small" 
              @click="deleteUser(row)"
              v-if="row.id !== currentUserId"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加用户对话框 -->
    <el-dialog v-model="showAddUserModal" title="➕ 添加用户" width="600px">
      <el-form :model="userForm" ref="userFormRef" label-width="100px">
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="userForm.userName" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱地址" />
        </el-form-item>
        <el-form-item label="角色" prop="roleName">
          <el-select v-model="userForm.roleName" placeholder="选择角色" style="width: 100%;">
            <el-option 
              v-for="role in roles" 
              :key="role.id" 
              :label="role.roleName" 
              :value="role.roleName" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="userForm.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="userForm.confirmPassword" type="password" placeholder="请再次输入密码" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeAddUserModal">取消</el-button>
          <el-button type="primary" @click="handleAddUser">
            <el-icon><Check /></el-icon>
            添加用户
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑用户对话框 -->
    <el-dialog v-model="showEditUserModal" title="✏️ 编辑用户" width="600px">
      <el-form :model="editUserForm" ref="editUserFormRef" label-width="100px">
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="editUserForm.userName" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="editUserForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editUserForm.email" placeholder="请输入邮箱地址" />
        </el-form-item>
        <el-form-item label="角色" prop="roleName">
          <el-select v-model="editUserForm.roleName" placeholder="选择角色" style="width: 100%;">
            <el-option 
              v-for="role in roles" 
              :key="role.id" 
              :label="role.roleName" 
              :value="role.roleName" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="editUserForm.status">
            <el-radio :label="1">活跃</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeEditUserModal">取消</el-button>
          <el-button type="primary" @click="handleEditUser">
            <el-icon><Check /></el-icon>
            保存修改
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Check, Refresh } from '@element-plus/icons-vue'
import { querySysUser, addSysUserAPI, updateSysUserAPI, deleteSysUserAPI, querySysRoleAPI } from '@/apis/sysAPI'

// 响应式数据
const searchQuery = ref('')
const roleFilter = ref('')
const statusFilter = ref('')
const showAddUserModal = ref(false)
const showEditUserModal = ref(false)
const currentUserId = ref(1) // 当前登录用户ID
const loading = ref(false)
const roles = ref([]) // 角色列表

// 用户表单
const userForm = ref({
  userName: '',
  phone: '',
  email: '',
  roleName: '',
  password: '',
  confirmPassword: ''
})

const editUserForm = ref({
  id: null,
  userName: '',
  phone: '',
  email: '',
  roleName: '',
  status: 1
})

// 用户数据
const users = ref([])

// 计算属性
const filteredUsers = computed(() => {
  let filtered = users.value

  // 搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    filtered = filtered.filter(user => 
      (user.userName && user.userName.toLowerCase().includes(query)) ||
      (user.email && user.email.toLowerCase().includes(query)) ||
      (user.phone && user.phone.includes(query))
    )
  }

  // 角色过滤
  if (roleFilter.value) {
    filtered = filtered.filter(user => user.roleName === roleFilter.value)
  }

  // 状态过滤
  if (statusFilter.value) {
    filtered = filtered.filter(user => user.status.toString() === statusFilter.value)
  }

  return filtered
})

// 方法
const getRoleText = (role) => {
  const roleMap = {
    admin: '管理员',
    dormitory: '宿管员',
    maintainer: '维修员'
  }
  return roleMap[role] || role
}

const getRoleTagType = (roleName) => {
  const tagTypeMap = {
    '超级管理员': 'danger',
    '宿舍管理员': 'success',
    '学生': 'warning'
  }
  return tagTypeMap[roleName] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    1: '活跃',
    0: '禁用'
  }
  return statusMap[status] || '未知'
}

const getStatusTagType = (status) => {
  const tagTypeMap = {
    1: 'success',
    0: 'danger'
  }
  return tagTypeMap[status] || 'info'
}

const formatDate = (dateString) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

// 获取角色列表
const fetchRoles = async () => {
  try {
    const response = await querySysRoleAPI()
    if (response.data && response.code === 0) {
      roles.value = response.data
    } else {
      ElMessage.error('获取角色列表失败')
    }
  } catch (error) {
    console.error('获取角色列表失败:', error)
    ElMessage.error('获取角色列表失败')
  }
}

// 获取用户数据
const fetchUsers = async () => {
  try {
    loading.value = true
    const response = await querySysUser()
    if (response.data && response.code === 0) {
      users.value = response.data
    } else {
      ElMessage.error('获取用户数据失败')
    }
  } catch (error) {
    console.error('获取用户数据失败:', error)
    ElMessage.error('获取用户数据失败')
  } finally {
    loading.value = false
  }
}

const refreshUsers = () => {
  fetchUsers()
}

const viewUser = (user) => {
  console.log('查看用户:', user)
}

const editUser = (user) => {
  editUserForm.value = {
    id: user.id,
    userName: user.userName,
    phone: user.phone,
    email: user.email,
    roleName: user.roleName,
    status: user.status
  }
  showEditUserModal.value = true
}

const deleteUser = async (user) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户 ${user.userName} 吗？此操作不可撤销。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    loading.value = true
    const response = await deleteSysUserAPI(user.id)
    if (response.data && response.code===0) {
      ElMessage.success('用户删除成功')
      fetchUsers() // 重新获取用户列表
    } else {
      ElMessage.error(response.data?.message || '删除用户失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除用户失败:', error)
      ElMessage.error('删除用户失败')
    }
  } finally {
    loading.value = false
  }
}

const handleAddUser = async () => {
  if (userForm.value.password !== userForm.value.confirmPassword) {
    ElMessage.error('两次输入的密码不一致')
    return
  }

  try {
    loading.value = true
    const params = {
      userName: userForm.value.userName,
      phone: userForm.value.phone,
      email: userForm.value.email,
      roleName: userForm.value.roleName,
      password: userForm.value.password,
      status: 1
    }
    
    const response = await addSysUserAPI(params)
    if (response.data && response.code===0) {
      ElMessage.success('用户添加成功')
      closeAddUserModal()
      fetchUsers() // 重新获取用户列表
    } else {
      ElMessage.error(response.data?.message || '添加用户失败')
    }
  } catch (error) {
    console.error('添加用户失败:', error)
    ElMessage.error('添加用户失败')
  } finally {
    loading.value = false
  }
}

const handleEditUser = async () => {
  try {
    loading.value = true
    const params = {
      id: editUserForm.value.id,
      userName: editUserForm.value.userName,
      phone: editUserForm.value.phone,
      email: editUserForm.value.email,
      roleName: editUserForm.value.roleName,
      status: editUserForm.value.status
    }
    
    const response = await updateSysUserAPI(params)
    if (response.data && response.code===0) {
      ElMessage.success('用户信息更新成功')
      closeEditUserModal()
      fetchUsers() // 重新获取用户列表
    } else {
      ElMessage.error(response.data?.message || '更新用户信息失败')
    }
  } catch (error) {
    console.error('更新用户信息失败:', error)
    ElMessage.error('更新用户信息失败')
  } finally {
    loading.value = false
  }
}

const closeAddUserModal = () => {
  showAddUserModal.value = false
  userForm.value = {
    userName: '',
    phone: '',
    email: '',
    roleName: '',
    password: '',
    confirmPassword: ''
  }
}

const closeEditUserModal = () => {
  showEditUserModal.value = false
  editUserForm.value = {
    id: null,
    userName: '',
    phone: '',
    email: '',
    roleName: '',
    status: 1
  }
}

onMounted(() => {
  // 初始化数据
  fetchUsers()
  fetchRoles() // 获取角色列表
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.search-section {
  margin-bottom: 16px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 0.75rem;
}

.user-avatar {
  width: 2.5rem;
  height: 2.5rem;
  border-radius: 50%;
  overflow: hidden;
  background: var(--bg-secondary);
  display: flex;
  align-items: center;
  justify-content: center;
}

.user-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-placeholder {
  font-size: 1rem;
  font-weight: 600;
  color: var(--text-primary);
}

.user-details {
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
}

.user-name {
  font-weight: 500;
  color: var(--text-primary);
}

.user-email {
  font-size: 0.75rem;
  color: var(--text-muted);
}
</style>